<template>
  <div>
    <!-- 零售单查询 -->
    <TopFilter ref="TopFilter" :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" isSubmitBtn @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhRetailOrders"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="downHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="visible" :title="drawerTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SonModel :type="handleType" :rowData="formData" @close="emitCloseHandler" />
    </Drawer>
    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, exportExcel, exporturl, getBrandAll, getSeriesAll, getModelAll, getConfigAll, getColorAll, getTrimAll } from '@/api/omSale/ActualSales/RetailOrders';
import { exportExcelFile } from '@/utils/index';
import SonModel from './SonModel';
import OwnerSearch from './OwnerSearch';
export default {
  name: 'RetailOrders',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    this.conf = { show: '明细' };
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      exportLoading: false,
      visible: false,
      isDealer: false,
      handleType: '',
      drawerTitle: ''
    };
  },
  components: {
    SonModel,
    OwnerSearch
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getBrand();
    this.getColorTrim();
  },
  methods: {
    // 搜索
    changeHandle(params) {
      this.fetchParams.xhrAbort = false;
      // params.notStatus = '60341006, 60341007, 60341008';
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      console.log('重置');
      this.topFilterList.find(x => x.fieldName == 'configId').initialValue = '';
      this.topFilterList.find(x => x.fieldName == 'configId').itemList = [];
      const str = this.topFilterList.find(x => x.fieldName == 'configId');
      console.log(str);
      this.$refs.TopFilter.RESET_FORM();
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 下载
    async downHandle() {
      let json = Object.assign({}, { CODE: 'CODE_1000003' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;
      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '零售订单查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    // 明细
    detailHandle(row) {
      this.handleType = 'show';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.drawerTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    emitCloseHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler1(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    selectChangeHandle(row) {},

    createdFrom() {
      return [
        {
          type: 'TEXT_AREA',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'TEXT_AREA',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入',
          maxlength: '',
          maxRows: 2
        },
        {
          type: 'INPUT',
          label: '零售订单号',
          fieldName: 'soNo',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '请输入'
        },

        {
          type: 'INPUT',
          label: '客户手机号',
          fieldName: 'customerTel',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '零售订单状态',
          fieldName: 'soStatus',
          placeholder: '请选择',
          // itemList: this.createDictList('6034', [60341006, 60341007, 60341008])
          itemList: this.createDlrDictList('2702')
        },
        // {
        //   type: 'SELECT',
        //   label: '开票状态',
        //   fieldName: 'Status',
        //   placeholder: '请选择',
        //   // itemList: this.createDictList('6034', [60341006, 60341007, 60341008])
        //   itemList: this.createDictList('6034')
        // },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brandId',
          disabled: false,
          placeholder: '请选择',
          itemList: [],
          change: val => {
            //调用方法
            this.changeSeriesList(val);
          }
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          disabled: false,
          placeholder: '请选择',
          itemList: [],
          change: val => {
            //调用方法
            this.changeModelList(val);
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelId',
          disabled: false,
          placeholder: '请选择',
          itemList: [],
          change: val => {
            //调用方法
            this.changeConfigList(val);
          }
        },
        {
          type: 'SELECT',
          label: '配置',
          fieldName: 'configId',
          disabled: false,
          placeholder: '请选择',
          itemList: []
        },
        { type: 'SELECT', label: '外饰', fieldName: 'colorId', filterable: true, disabled: false, placeholder: '请选择', itemList: [] },
        { type: 'SELECT', label: '内饰', fieldName: 'trimId', filterable: true, disabled: false, placeholder: '请选择', itemList: [] },
        {
          type: 'INPUT',
          label: '物料编码',
          fieldName: 'productCode',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '物料描述',
          fieldName: 'productName',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '零售订单创建时间',
          dataIndex: 'sheetCreateDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '零售单号',
          dataIndex: 'soNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '开票人',
        //   dataIndex: 'drawerName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '客户',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户手机号',
          dataIndex: 'customerTel',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '零售订单状态',
          dataIndex: 'soStatus',
          showOverflowTooltip: true,
          sorter: false,
          filter: false,
          align: 'left',
          filterType: 'input',
          render: props => {
            return <span>{this.createDlrDictText(props.row.soStatus, '2702')}</span>;
          }
        },
        {
          title: '配车状态',
          dataIndex: 'dispatchedStatus',
          showOverflowTooltip: true,
          sorter: false,
          filter: false,
          align: 'left',
          filterType: 'input',
          render: props => {
            return <span>{this.createDlrDictText(props.row.dispatchedStatus, '2653')}</span>;
          }
        },
        {
          title: '配车时间',
          dataIndex: 'dispatchedData',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '开票状态',
        //   dataIndex: 'status',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '开票时间',
        //   dataIndex: 'kptime',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '实际交车时间',
          dataIndex: 'handoverTime',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车辆是否出库',
          dataIndex: 'isDelivery',
          showOverflowTooltip: true,
          sorter: false,
          filter: false,
          align: 'left',
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.isDelivery, '1004')}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          align: 'center',
          width: 180,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          align: 'center',
          width: 250,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultantName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单取消时间',
          dataIndex: 'cancelTime',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },

    //品牌改变时查询车系
    async changeSeriesList(brandId) {
      this.topFilterList.find(item => item.fieldName === 'seriesId').initialValue = null;
      this.topFilterList.find(item => item.fieldName === 'modelId').initialValue = null;
      this.topFilterList.find(item => item.fieldName === 'configId').initialValue = null;

      this.topFilterList.find(item => item.fieldName === 'seriesId').itemList = [];
      this.topFilterList.find(item => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find(item => item.fieldName === 'configId').itemList = [];

      if (!brandId) return;
      console.log('11111');
      let requestDTO = {
        brandId: brandId
      };
      const res = await getSeriesAll(requestDTO);
      let seriesDict = res.data.map(x => ({
        text: x.seriesName,
        value: x.seriesId
      }));
      this.topFilterList.find(item => item.fieldName === 'seriesId').itemList = seriesDict;
    },
    //车系改变时查询车型
    async changeModelList(seriesId) {
      this.topFilterList.find(item => item.fieldName === 'modelId').initialValue = null;
      this.topFilterList.find(item => item.fieldName === 'configId').initialValue = null;

      this.topFilterList.find(item => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find(item => item.fieldName === 'configId').itemList = [];
      if (!seriesId) return;
      let requestDTO = {
        seriesId: seriesId
      };
      const res = await getModelAll(requestDTO);
      let modelDict = res.data.map(x => ({
        text: x.modelName,
        value: x.modelId
      }));
      this.topFilterList.find(item => item.fieldName === 'modelId').itemList = modelDict;
    },
    //车型改变时查询配置
    async changeConfigList(modelId) {
      this.topFilterList.find(item => item.fieldName === 'configId').initialValue = null;
      this.topFilterList.find(item => item.fieldName === 'configId').itemList = [];
      if (!modelId) return;
      let requestDTO = {
        modelId: modelId
      };

      const res = await getConfigAll(requestDTO);
      let configDict = res.data.map(x => ({
        text: x.configName,
        value: x.configId
      }));
      this.topFilterList.find(item => item.fieldName === 'configId').itemList = configDict;
    },
    // 获取品牌
    async getBrand() {
      const res = await getBrandAll();
      if (!res || !res.data) return;
      this.topFilterList.find(item => item.fieldName === 'brandId').itemList = res.data.map(x => ({
        text: x.brandName,
        value: x.brandId
      }));
    },
    //颜色 内饰
    async getColorTrim() {
      const color = await getColorAll();
      const trim = await getTrimAll();
      if (!color || !color.data) return;
      this.topFilterList.find(item => item.fieldName === 'colorId').itemList = color.data.map(x => ({
        text: x.colorName,
        value: x.colorId
      }));
      if (!trim || !trim.data) return;
      this.topFilterList.find(item => item.fieldName === 'trimId').itemList = trim.data.map(x => ({
        text: x.colorName,
        value: x.colorId
      }));
    }
  }
};
</script>
